<template>
  <el-form
    v-show="getShow"
    ref="formLogin"
    :model="loginData.loginForm"
    :rules="LoginRules"
    class="login-form glass-form"
    label-position="top"
    label-width="120px"
    size="large"
  >
    <div class="space-y-6">
      <div class="text-center mb-8">
        <LoginFormTitle class="w-full" />
        <p class="text-white/60 text-sm mt-2">请输入您的账号信息</p>
      </div>

      <div class="space-y-4">
        <el-form-item prop="username" class="custom-form-item">
          <el-input
            v-model="loginData.loginForm.username"
            :placeholder="t('login.usernamePlaceholder')"
            :prefix-icon="iconAvatar"
            class="custom-input"
            size="large"
          />
        </el-form-item>
        
        <el-form-item prop="password" class="custom-form-item">
          <el-input
            v-model="loginData.loginForm.password"
            :placeholder="t('login.passwordPlaceholder')"
            :prefix-icon="iconLock"
            show-password
            type="password"
            class="custom-input"
            size="large"
            @keyup.enter="getCode()"
          />
        </el-form-item>
      </div>
      <div class="flex items-center justify-between text-sm">
        <el-checkbox v-model="loginData.loginForm.rememberMe" class="custom-checkbox">
          <span class="text-white/80">{{ t('login.remember') }}</span>
        </el-checkbox>
        <el-link
          class="custom-link"
          @click="setLoginState(LoginStateEnum.RESET_PASSWORD)"
        >
          {{ t('login.forgetPassword') }}
        </el-link>
      </div>
      <el-form-item class="mt-6">
        <XButton
          :loading="loginLoading"
          :title="t('login.login')"
          class="w-full custom-login-btn"
          type="primary"
          size="large"
          @click="getCode()"
        />
      </el-form-item>
      <Verify
        v-if="loginData.captchaEnable === 'true'"
        ref="verify"
        :captchaType="captchaType"
        :imgSize="{ width: '400px', height: '200px' }"
        mode="pop"
        @success="handleLogin"
      />
      <!-- 分割线 -->
      <div class="flex items-center my-6">
        <div class="flex-1 h-px bg-gradient-to-r from-transparent via-white/20 to-transparent"></div>
      </div>
      
      <!-- 社交登录图标 -->
      <div class="flex justify-center space-x-4 mb-4">
        <div
          v-for="item in socialList"
          :key="item.type"
          class="social-icon"
          @click="doSocialLogin(item.type)"
        >
          <Icon :icon="item.icon" :size="20" />
        </div>
      </div>
      
      <!-- 其他登录方式按钮 -->
      <div class="flex justify-center space-x-4">
        <button
          type="button"
          class="custom-text-btn"
          @click="setLoginState(LoginStateEnum.MOBILE)"
        >
          {{ t('login.btnMobile') }}
        </button>
        <span class="text-white/30">|</span>
        <button
          type="button"
          class="custom-text-btn"
          @click="setLoginState(LoginStateEnum.QR_CODE)"
        >
          {{ t('login.btnQRCode') }}
        </button>
        <span class="text-white/30">|</span>
        <button
          type="button"
          class="custom-text-btn"
          @click="setLoginState(LoginStateEnum.REGISTER)"
        >
          {{ t('login.btnRegister') }}
        </button>
      </div>

    </div>
  </el-form>
</template>
<script lang="ts" setup>
import { ElLoading } from 'element-plus'
import LoginFormTitle from './LoginFormTitle.vue'
import type { RouteLocationNormalizedLoaded } from 'vue-router'

import { useIcon } from '@/hooks/web/useIcon'

import * as authUtil from '@/utils/auth'
import { usePermissionStore } from '@/store/modules/permission'
import * as LoginApi from '@/api/login'
import { LoginStateEnum, useFormValid, useLoginState } from './useLogin'

defineOptions({ name: 'LoginForm' })

const { t } = useI18n()
const message = useMessage()
const iconHouse = useIcon({ icon: 'ep:house' })
const iconAvatar = useIcon({ icon: 'ep:avatar' })
const iconLock = useIcon({ icon: 'ep:lock' })
const formLogin = ref()
const { validForm } = useFormValid(formLogin)
const { setLoginState, getLoginState } = useLoginState()
const { currentRoute, push } = useRouter()
const permissionStore = usePermissionStore()
const redirect = ref<string>('')
const loginLoading = ref(false)
const verify = ref()
const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN)

const LoginRules = {
  username: [required],
  password: [required]
}
const loginData = reactive({
  isShowPassword: false,
  captchaEnable: import.meta.env.VITE_APP_CAPTCHA_ENABLE,
  loginForm: {
    username: import.meta.env.VITE_APP_DEFAULT_LOGIN_USERNAME || '',
    password: import.meta.env.VITE_APP_DEFAULT_LOGIN_PASSWORD || '',
    captchaVerification: '',
    rememberMe: true // 默认记录我。如果不需要，可手动修改
  }
})

const socialList = [
  { icon: 'ant-design:wechat-filled', type: 30 },
  { icon: 'ant-design:dingtalk-circle-filled', type: 20 },
  { icon: 'ant-design:github-filled', type: 0 },
  { icon: 'ant-design:alipay-circle-filled', type: 0 }
]

// 获取验证码
const getCode = async () => {
  // 情况一，未开启：则直接登录
  if (loginData.captchaEnable === 'false') {
    await handleLogin({})
  } else {
    // 情况二，已开启：则展示验证码；只有完成验证码的情况，才进行登录
    // 弹出验证码
    verify.value.show()
  }
}

// 记住我
const getLoginFormCache = () => {
  const loginForm = authUtil.getLoginForm()
  if (loginForm) {
    loginData.loginForm = {
      ...loginData.loginForm,
      username: loginForm.username ? loginForm.username : loginData.loginForm.username,
      password: loginForm.password ? loginForm.password : loginData.loginForm.password,
      rememberMe: loginForm.rememberMe
    }
  }
}

const loading = ref() // ElLoading.service 返回的实例
// 登录
const handleLogin = async (params: any) => {
  loginLoading.value = true
  try {
    const data = await validForm()
    if (!data) {
      return
    }
    const loginDataLoginForm = { ...loginData.loginForm }
    loginDataLoginForm.captchaVerification = params.captchaVerification
    const res = await LoginApi.login(loginDataLoginForm)
    if (!res) {
      return
    }
    loading.value = ElLoading.service({
      lock: true,
      text: '正在加载系统中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    if (loginDataLoginForm.rememberMe) {
      authUtil.setLoginForm(loginDataLoginForm)
    } else {
      authUtil.removeLoginForm()
    }
    authUtil.setToken(res)
    if (!redirect.value) {
      redirect.value = '/'
    }
    // 判断是否为SSO登录
    if (redirect.value.indexOf('sso') !== -1) {
      window.location.href = window.location.href.replace('/login?redirect=', '')
    } else {
      await push({ path: redirect.value || permissionStore.addRouters[0].path })
    }
  } finally {
    loginLoading.value = false
    loading.value.close()
  }
}

// 社交登录
const doSocialLogin = async (type: number) => {
  if (type === 0) {
    message.error('此方式未配置')
  } else {
    loginLoading.value = true
    // 计算 redirectUri
    // 注意: type、redirect 需要先 encode 一次，否则钉钉回调会丢失。
    // 配合 social-login.vue#getUrlValue() 使用
    const redirectUri =
      location.origin +
      '/social-login?' +
      encodeURIComponent(`type=${type}&redirect=${redirect.value || '/'}`)

    // 进行跳转
    window.location.href = await LoginApi.socialAuthRedirect(type, encodeURIComponent(redirectUri))
  }
}
watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)
onMounted(() => {
  getLoginFormCache()
})
</script>

<style lang="scss" scoped>
.glass-form {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  padding: 2rem;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.custom-form-item {
  :deep(.el-form-item__error) {
    color: #ff6b6b;
    background: rgba(255, 107, 107, 0.1);
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
  }
}

.custom-input {
  :deep(.el-input__wrapper) {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 12px;
    box-shadow: none;
    transition: all 0.3s ease;
    
    &:hover {
      border-color: rgba(255, 255, 255, 0.4);
      background: rgba(255, 255, 255, 0.15);
    }
    
    &.is-focus {
      border-color: rgba(6, 182, 212, 0.8);
      background: rgba(255, 255, 255, 0.2);
      box-shadow: 0 0 0 2px rgba(6, 182, 212, 0.2);
    }
  }
  
  :deep(.el-input__inner) {
    color: white;
    
    &::placeholder {
      color: rgba(255, 255, 255, 0.6);
    }
  }
  
  :deep(.el-input__prefix-inner) {
    color: rgba(255, 255, 255, 0.7);
  }
  
  :deep(.el-input__suffix-inner) {
    color: rgba(255, 255, 255, 0.7);
  }
}

.custom-checkbox {
  :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
    background-color: #06b6d4;
    border-color: #06b6d4;
  }
  
  :deep(.el-checkbox__inner) {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(255, 255, 255, 0.3);
    
    &:hover {
      border-color: #06b6d4;
    }
  }
}

.custom-login-btn {
  :deep(.el-button) {
    background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
    border: none;
    border-radius: 12px;
    font-weight: 600;
    letter-spacing: 0.5px;
    transition: all 0.3s ease;
    box-shadow: 0 4px 15px rgba(6, 182, 212, 0.4);
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(6, 182, 212, 0.6);
    }
    
    &:active {
      transform: translateY(0);
    }
  }
}

.custom-alt-btn {
  :deep(.el-button) {
    background: transparent;
    border: 1px solid rgba(255, 255, 255, 0.1);
    color: rgba(255, 255, 255, 0.7);
    border-radius: 12px;
    transition: all 0.3s ease;
    font-weight: 400;
    font-size: 14px;
    
    &:hover {
      background: rgba(6, 182, 212, 0.1);
      border-color: rgba(6, 182, 212, 0.3);
      color: #06b6d4;
      transform: none;
    }
    
    &:focus {
      background: rgba(6, 182, 212, 0.1);
      border-color: rgba(6, 182, 212, 0.3);
      color: #06b6d4;
    }
  }
}

.social-icon {
  color: rgba(255, 255, 255, 0.6);
  padding: 8px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  
  &:hover {
    color: white;
    background: rgba(255, 255, 255, 0.2);
  }
}

.custom-link {
  :deep(.el-link__inner) {
    color: rgba(255, 255, 255, 0.8);
    transition: all 0.3s ease;
    
    &:hover {
      color: #06b6d4;
      text-decoration: underline;
    }
  }
}

.custom-text-btn {
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  font-weight: 400;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 4px 8px;
  border-radius: 4px;
  
  &:hover {
    color: #06b6d4;
    background: rgba(6, 182, 212, 0.1);
  }
  
  &:focus {
    outline: none;
    color: #06b6d4;
    background: rgba(6, 182, 212, 0.1);
  }
}

.login-code {
  float: right;
  width: 100%;
  height: 38px;

  img {
    width: 100%;
    height: auto;
    max-width: 100px;
    vertical-align: middle;
    cursor: pointer;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .glass-form {
    padding: 1.5rem;
    border-radius: 12px;
  }
  
  .custom-login-btn {
    :deep(.el-button) {
      font-size: 14px;
      padding: 12px 20px;
    }
  }
  
  .custom-alt-btn {
    :deep(.el-button) {
      font-size: 13px;
      padding: 8px 16px;
    }
  }
}

@media (max-width: 480px) {
  .glass-form {
    padding: 1rem;
    margin: 0.5rem;
  }
  
  .social-icon {
    padding: 6px;
    font-size: 14px;
  }
  
  .custom-input {
    :deep(.el-input__wrapper) {
      border-radius: 8px;
    }
  }
  
  .custom-login-btn {
    :deep(.el-button) {
      border-radius: 8px;
      font-size: 13px;
    }
  }
}
</style>
